package com.sghd.football.module.game.service.core;

import com.sghd.common.utils.json.JsonUtils;
import com.sghd.football.module.data.entity.GameLine;
import com.sghd.football.module.game.service.model.Result;

import java.util.*;

/**
 * 规则计算服务
 */
public class Rule {

    /** 定义线规则*/
    public static List<Integer[]> lines = new ArrayList<>();

    public static Set<Integer> oneThreeFive = new HashSet<>();//获得免费游戏的列1,3,5

    public static void init(List<GameLine> gameLines){
        oneThreeFive.addAll(Arrays.asList(1,3,5));
        lines.clear();
        for (GameLine gameLine : gameLines) {
           Integer[] line = JsonUtils.string2Array(gameLine.getLine(), Integer.class);
           lines.add(line);
        }
    }

    /**
     * 计算游戏结果
     * @param grids
     * @return
     */
    public static Result calc(Grid[] grids, int row) {
        Result result = new Result();
        Grid firsGrid = new Grid();//记录临时结果，减少数组复制
        for (int lineIdx = 0; lineIdx < lines.size(); lineIdx++) {//处理连线
            Integer[] idxs = lines.get(lineIdx);
            Grid tpl = grids[idxs[0]];//每条线第一个元素
            firsGrid.clean();
            firsGrid.setChess(tpl.getChess());
            if(firsGrid.getChess().isSpecial()){//特殊元素不处理
                continue;
            }
            firsGrid.added(idxs[0]);
            for (int idx = 1; idx < idxs.length; idx++) {
                int gridIdx = idxs[idx];
                Grid nextGrid = grids[gridIdx];
                if (firsGrid.equals(nextGrid)) {
                    firsGrid.added(gridIdx);
                    if (firsGrid.getChess() == ChessType.CT_WILD) {
                        firsGrid.setChess(nextGrid.getChess());
                    }
                } else {
                    break;
                }
            }
            firsGrid.checkResult(lineIdx, result, grids);
        }
        //处理特殊元素
        Set<Integer> scatter = new HashSet<>();//ChessType.CT_SCATTER 出现的列
        Set<Integer> bounds = new HashSet<>();//ChessType.BOUNDS 出现的列

        List<Integer> list = new ArrayList<>();
        for(int i=0;i<grids.length;i++){
            Grid grid = grids[i];
            ChessType type = grid.getChess();
            list.add(type.ordinal());
            int col = i / row +1;//当前列
            if(type.equals(ChessType.CT_SCATTER)){
                scatter.add(col);
            }
            if(type.equals(ChessType.CT_BONUS)){
                bounds.add(col);
            }
        }
        if(scatter.containsAll(oneThreeFive)){
            result.setFreeGame(true);
        }
        if(bounds.size()>=3){
            result.setBounds(true);
        }
        result.setSequence(list);//旋转结束后的排列
        return result;
    }

    public static int size(){
        return lines.size();
    }
}

